import { StaticRouter,Route,matchPath } from 'react-router-dom';
var express = require('express');
var app = express();
import { renderToString  } from 'react-dom/server';
import React from 'react';
const path = require('path');
import Routes from './route.js';
import store from './redux/index.js';
import {Provider} from 'react-redux';
import { matchRoutes } from 'react-router-config';
import ehp from 'express-http-proxy';


// 静态文件
app.use(express.static('build'));

// 接口代理
app.use(
'/api',
ehp('localhost:12345', { // 代理到的目标服务器
    proxyReqPathResolver: function (req) {
        return '/ssr/api' + req.url;
    }
  })
);

app.get('*', function(req, res){
 const s = store();


  // 如果在这里能拿到store的数据，服务端就可以不依赖componentDidMount获取数据进行渲染了。 
  // 根据当前path得到到底应该加载哪部分数据。
  // 增加
  const ps = matchRoutes(Routes, req.path);

  // 叠加的会返回嵌套tree上所有匹配
  //console.log(ps);

  // 跑组件后面loaddata
  const promises = [];
  ps.forEach((v,i) => {
      const ld = v.route.loadData(s);
      ld && promises.push(ld);
  });  

  //console.log(promises); 

  // 服务端路由
  const ServerRouter = () => {
    return(
        <Provider store={s}>
            <StaticRouter context={{}} location={req.path}>
               {
                   Routes.map((route, i) => {
                       return <Route key={i} {...route} />
                   })
               }
            </StaticRouter>
       </Provider>
    )
  }

  Promise.all(promises).then(() => {
      res.send(`<html><body id="root">[[[${renderToString(<ServerRouter />)}]]]]<script>window.context={state:${JSON.stringify(s.getState())}}</script><script src="./test.bundle.js"></script></body></html>`);
  });
});
console.log(123);
app.listen(8888);
